# !/usr/bin/env python
# -*- coding:utf-8 -*-
'''图表

历史:
    2019-05-18 姚彧 创建
'''

__all__ = ['paneChart']

from PyQt5.QtWidgets import QDockWidget
from PyQt5.QtCore import Qt
from events.EventCenter import (EventContext, EventDispatcher)
from tool.Singleton import Singleton
# 使用 matplotlib中的FigureCanvas (在使用 Qt5 Backends中 FigureCanvas继承自QtWidgets.QWidget)
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

class paneChart(QDockWidget, Singleton):
    def __init__(self):
        super().__init__('绘图')
        self.__init_ui()

    def emit(self, *args, **kwargs):
        return EventDispatcher().emit(*args, **kwargs)

    def __init_ui(self):
        self.figure = plt.figure(facecolor='#FFD7C4') #可选参数,facecolor为背景颜色
        self.canvas = FigureCanvas(self.figure)
        self.setFeatures(QDockWidget.DockWidgetFloatable)
        self.setWidget(self.canvas)

        context = EventContext(pane_args = (Qt.RightDockWidgetArea, self))
        self.emit('UI.Dock.Add', context)


    def on_event_draw(self, context:EventContext, *args, **kwargs):
        assert context.path == 'on_draw'
        df = context['df'].sort_index()
        column = context.get('column', '基本每股收益(元)')
        plt.cla()
        # ax = plt.subplot(111)
        plt.plot(df.index, df[column], marker = "v")
        xmajorLocator = MultipleLocator(4)
        plt.gca().xaxis.set_major_locator(xmajorLocator)
        # plt.xticks(df.index[:5], rotation=60)
        self.canvas.draw()


    @classmethod
    def register_events(cls):
        EventDispatcher().register('on_draw', cls.getInstance().on_event_draw)
